Page({
    data: {
        supplier_type: '', //供应商类型 0普通供应商  1批发供应商
        info: null,
        chooseGoodsInfo: null, //选择的商品
        goodsNameErr: false,
        price: '', //普通供应价格
        priceErr: false,
        purchase_price: '', //批发供应价
        purchase_priceErr: false,
        goodsPropertyPopup: false, //展示商品属性选择弹出层
        goodsPropsList: [], //获取到的商品可选择属性列表
        attr: '', //已选择的属性名称
        attrErr: false,
        stock: '', //库存
        stockErr: false,
        sellNum: '', //起售数量
        sellNumErr: false,
        quotaNum: '', //每人限购数量
        video_fileList: [], //本地商品视频列表
        video: '', //上传至服务器商品视频地址
        goods_img: '',
        goods_imgErr: false,
        goods_img_fileList: [], //商品图片
        detailText: '', //商品介绍
        detailTextErr: false,
        buttonLoading: false,
    },
    onLoad: function (options) {
        wx.setNavigationBarTitle({
            title: options.id != undefined ? '编辑商品' : '添加商品',
        });

        this.setData({
            supplier_type: Number(options.supplier_type),
        });

        if (options.id != undefined) {
            wx.showLoading({
                title: '加载中',
                mask: true,
            });
            return this.getGoodsInfo(options.id);
        }
        //获取商品属性选项列表
        this.getGoodsProp();
    },
    //获取商品信息
    getGoodsInfo(product_id) {
        this.request(
            {
                url: '/supplier/product/detail',
                data: { product_id },
            },
            res => {
                //同步商品图片
                let goods_img_fileList = [];
                let goods_img = [];
                res.data.photo_list.forEach(item => {
                    goods_img_fileList.push({
                        type: 'image',
                        status: 'done',
                        url: this.data.imgHost + item.photo,
                        path: item.photo,
                    });
                    goods_img.push(item.photo);
                });
                //同步视频
                if (res.data.have_video === 1) {
                    //有视频
                    this.setData({
                        video: [res.data.video],
                        video_fileList: [
                            {
                                type: 'video',
                                status: 'done',
                                url: this.data.imgHost + res.data.video,
                                path: this.data.imgHost + res.data.video,
                            },
                        ],
                    });
                }
                this.setData({
                    info: res.data,
                    chooseGoodsInfo: {
                        product_common_id: res.data.product_common_id,
                        product_name: res.data.product_name,
                    },
                    price: res.data.cost_price,
                    purchase_price: res.data.purchase_price,
                    stock: res.data.sku,
                    goods_img_fileList,
                    goods_img,
                    detailText: res.data.intro,
                    sellNum: res.data.sell_num,
                    quotaNum: res.data.quota_num,
                });
                //获取商品属性选项列表
                this.getGoodsProp();
            }
        );
    },
    //点击选择商品
    toChooseGoods() {
        if (this.data.info != null) return;
        wx.navigateTo({
            url: '/pages/good_add_choose/index',
            events: {
                // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                acceptDataFromOpenedPage: ({ goodsInfo }) => {
                    this.setData({ chooseGoodsInfo: goodsInfo });
                },
            },
        });
        this.clearErr();
    },
    //获取商品属性选项列表
    getGoodsProp() {
        this.request(
            {
                url: '/supplier/com/product/attr',
            },
            res => {
                wx.hideLoading();
                res.data.unshift({
                    attr_name: '等级',
                    customAttr: true,
                    attr_value: [
                        { attr_value_name: 'A级' },
                        { attr_value_name: 'B级' },
                        { attr_value_name: 'C级' },
                        { attr_value_name: 'D级' },
                        { attr_value_name: 'E级' },
                        { attr_value_name: 'O级' },
                        { attr_value_name: 'G级' },
                    ],
                });
                res.data.forEach(item => {
                    item.active = null; //生效的属性
                    item.active_copy = null; //当前选中属性
                });
                //如果是编辑商品，同步选中商品属性
                let attr = [];
                if (this.data.info != null) {
                    this.data.info.attr_list.forEach(item => {
                        attr.push(item.attr_name);
                        //匹配属性位置索引
                        const attrIndex = res.data.findIndex(i => {
                            return i.attr_id === item.attr_id;
                        });
                        //匹配属性值索引
                        const attrValueIndex = res.data[attrIndex].attr_value.findIndex(i => {
                            return i.attr_value_id === item.attr_value[0].attr_value_id;
                        });
                        res.data[attrIndex].active = attrValueIndex;
                        res.data[attrIndex].active_copy = attrValueIndex;
                    });
                    //匹配等级
                    if (this.data.info.level) {
                        const index = res.data[0].attr_value.findIndex(item => {
                            return item.attr_value_name === this.data.info.level + '级';
                        });
                        res.data[0].active = index;
                        res.data[0].active_copy = index;
                        attr.unshift('等级');
                    }
                }
                this.setData({
                    goodsPropsList: res.data,
                    attr: attr.join(','),
                });
            }
        );
    },
    //打开商品属性选择弹出层
    toChooseGoodsAttr() {
        this.setData({ goodsPropertyPopup: true });
        this.clearErr();
    },
    //选择商品属性
    chooseAttr({ mark }) {
        const { index, childrenIndex } = mark;
        if (childrenIndex == undefined) return;
        if (this.data.goodsPropsList[index].active_copy === childrenIndex) {
            this.setData({
                ['goodsPropsList[' + index + '].active_copy']: null,
            });
        } else {
            this.setData({
                ['goodsPropsList[' + index + '].active_copy']: childrenIndex,
            });
        }
    },
    //重置商品属性
    reset() {
        let { goodsPropsList } = this.data;
        goodsPropsList.forEach(item => {
            item.active_copy = null;
        });
        this.setData({ goodsPropsList });
    },
    //确认选择商品属性
    confirm() {
        let { goodsPropsList } = this.data;
        let attr = [];
        goodsPropsList.forEach(item => {
            item.active = item.active_copy;
            if (item.active != null) attr.push(item.attr_name);
        });
        this.setData({
            goodsPropsList,
            attr: attr.join(','),
            goodsPropertyPopup: false,
        });
    },
    //关闭商品属性选择弹出层
    closeGoodsPropertyPopup() {
        let { goodsPropsList } = this.data;
        goodsPropsList.forEach(item => {
            item.active_copy = item.active;
        });
        this.setData({ goodsPropertyPopup: false, goodsPropsList });
    },
    //验证价格
    verification(e) {
        const { field } = e.currentTarget.dataset;
        let value = this.formatter(e.detail.value);
        value = value ? value : '';
        this.setData({
            [`${field}`]: this.formatter(value),
        });
    },
    /**验证金额输入 */
    formatter(value) {
        value = value.toString();
        value = value.replace(/[^\d.]/g, ''); //清除“数字”和“.”以外的字符
        value = value.replace(/\.{2,}/g, '.'); //只保留第一个. 清除多余的
        value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.');
        value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
        if (value.indexOf('.') < 0 && value != '') {
            //以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
            value = parseFloat(value);
        }
        value = parseFloat(value);
        if (Number.isNaN(value)) return '';
        return value;
    },
    //判断批发价格不能少于普通供应价格
    judgePrice() {
        const cost_price = Number(this.data.price);
        const wholesale_price = Number(this.data.purchase_price);
        if (wholesale_price > cost_price) {
            wx.showToast({
                title: '批发供应价不能大于普通供应价',
                icon: 'none',
                duration: 3000,
            });
            this.setData({
                priceErr: true,
                purchase_priceErr: true,
            });
            return false;
        } else {
            return true;
        }
    },
    //清除错误提示
    clearErr() {
        this.setData({
            goodsNameErr: false,
            priceErr: false,
            stockErr: false,
            attrErr: false,
            goods_imgErr: false,
            detailTextErr: false,
            purchase_priceErr: false,
            sellNumErr: false,
        });
    },
    //上传商品视频
    afterRead_video(event) {
        let that = this;
        const { file } = event.detail;
        let { video_fileList } = this.data;
        video_fileList = video_fileList.concat(file);
        this.setData({ video_fileList });
        this.data.video_fileList.forEach((item, index) => {
            if (item.status === 'done') return;
            this.setData({
                ['video_fileList[' + index + '].status']: 'uploading',
                ['video_fileList[' + index + '].message']: '上传中',
            });

            wx.uploadFile({
                url: that.data.host + '/supplier/upload/video',
                filePath: item.url,
                name: 'file',
                header: {
                    Authorization: wx.getStorageSync('Authorization'),
                },
                success(res) {
                    const data = JSON.parse(res.data);

                    if (data.code === 0) {
                        let uploaded = that.data.store_video || [];
                        const { path } = data.data;
                        console.log(data);
                        uploaded.push(path);
                        that.setData({
                            ['video_fileList[' + index + '].status']: 'done',
                            ['video_fileList[' + index + '].path']: path,
                            video: uploaded,
                        });
                    } else {
                        that.setData({
                            ['video_fileList[' + index + '].status']: 'failed',
                            ['video_fileList[' + index + '].message']: '上传失败',
                        });
                    }
                },
                fail() {
                    that.setData({
                        ['video_fileList[' + index + '].status']: 'failed',
                        ['video_fileList[' + index + '].message']: '上传失败',
                    });
                },
            });
        });
    },
    //删除上传的商品视频
    video_del(event) {
        const { index } = event.detail;
        this.delUpload('video', index);

        let { video } = this.data;
        video.splice(index, 1);
        this.setData({ video });
    },
    //上传商品图片
    afterRead_goods_img(event) {
        const { file } = event.detail;
        let { goods_img_fileList } = this.data;
        goods_img_fileList = goods_img_fileList.concat(file);
        this.setData({ goods_img_fileList });
        this.upload('goods_img_fileList');
    },
    //删除商品图片
    store_goods_del(event) {
        const { index } = event.detail;
        this.delUpload('goods_img', index);
    },
    //上传图片至服务器
    upload(propData) {
        let that = this;
        this.data[propData].forEach((item, index) => {
            if (item.status === 'done') return;
            this.setData({
                [propData + '[' + index + '].status']: 'uploading',
                [propData + '[' + index + '].message']: '上传中',
            });
            wx.uploadFile({
                url: this.data.host + '/supplier/upload/image',
                filePath: item.url,
                name: 'image',
                formData: { from: 'product' },
                header: {
                    Authorization: wx.getStorageSync('Authorization'),
                },
                success(res) {
                    const data = JSON.parse(res.data);
                    if (data.code === 0) {
                        const propoty = propData.replace('_fileList', '');
                        let uploaded = that.data[propoty] || [];
                        const { path } = data.data;
                        uploaded.push(path);
                        that.setData({
                            [propData + '[' + index + '].status']: 'done',
                            [propData + '[' + index + '].path']: path,
                            [propoty]: uploaded,
                        });
                    } else {
                        that.setData({
                            [propData + '[' + index + '].status']: 'failed',
                            [propData + '[' + index + '].message']: '上传失败',
                        });
                    }
                },
                fail() {
                    that.setData({
                        [propData + '[' + index + '].status']: 'failed',
                        [propData + '[' + index + '].message']: '上传失败',
                    });
                },
            });
        });
    },
    //删除已上传或上传失败的图片
    delUpload(propData, fileListIndex) {
        const path = this.data[propData + '_fileList'][fileListIndex].path;
        if (path) {
            const uploadIndex = this.data[propData].findIndex(item => {
                return item === path;
            });
            if (uploadIndex !== -1) {
                const newUploaded = this.data[propData];
                newUploaded.splice(uploadIndex, 1);
                this.setData({
                    [propData]: newUploaded,
                });
            }
        }
        let fileList = this.data[propData + '_fileList'];
        fileList.splice(fileListIndex, 1);
        this.setData({
            [propData + '_fileList']: fileList,
        });
    },
    uploadSizeOver() {
        wx.showToast({
            title: '上传文件大小不能超过5M',
            icon: 'none',
            duration: 2000,
        });
    },
    uploadVideoSizeOver() {
        wx.showToast({
            title: '上传文件大小不能超过20M',
            icon: 'none',
            duration: 2000,
        });
    },
    //确认添加
    add() {
        const {
            chooseGoodsInfo,
            goodsPropsList,
            stock,
            video_fileList,
            video,
            goods_img,
            goods_img_fileList,
            info,
            detailText,
            price,
            purchase_price,
            supplier_type,
            sellNum,
            quotaNum,
        } = this.data;
        if (chooseGoodsInfo == null) return this.setData({ goodsNameErr: true });

        //商品等级必填
        if (!goodsPropsList[0].customAttr || goodsPropsList[0].active == null) {
            this.setData({ attrErr: true });
            return wx.showToast({
                title: '商品属性[等级]为必选项',
                icon: 'none',
                duration: 3000,
            });
        }
        if (stock === '') return this.setData({ stockErr: true });
        if (sellNum === '') return this.setData({ sellNumErr: true });
        if (goods_img.length === 0) return this.setData({ goods_imgErr: true });
        //验证视频、图片上传中或者上传失败
        if (video_fileList.length && video_fileList[0].status !== 'done')
            return wx.showToast({
                title: '有视频正在上传中或者上传失败',
                icon: 'none',
                duration: 2000,
            });

        let flag = true;
        for (let i = 0; i < goods_img_fileList.length; i++) {
            if (goods_img_fileList[i].status !== 'done') {
                flag = false;
                break;
            }
        }

        if (!flag)
            return wx.showToast({
                title: '有图片正在上传中或者上传失败',
                icon: 'none',
                duration: 2000,
            });
        if (this.data.price === '') return this.setData({ priceErr: true });

        if (supplier_type === 1) {
            if (this.data.purchase_price === '') return this.setData({ purchase_priceErr: true });
            if (!this.judgePrice()) return;
        }

        this.setData({ buttonLoading: true });
        let reqData = {
            cost_price: price,
            sku: Number(stock),
            photos: goods_img,
            sell_num: Number(sellNum),
        };

        if (supplier_type === 1) {
            reqData.purchase_price = purchase_price;
        }

        info == null ? (reqData.product_common_id = chooseGoodsInfo.product_common_id) : (reqData.product_id = info.product_id);

        if (video.length) reqData.video = video[0];

        let goodsPropsList_copy = JSON.parse(JSON.stringify(goodsPropsList));
        let level = goodsPropsList_copy.shift();
        reqData.level = level.attr_value[level.active].attr_value_name.replaceAll('级', '');

        let attr = [];
        goodsPropsList_copy.forEach(item => {
            if (item.active != null) {
                attr.push(item.attr_value[item.active].attr_value_id);
            }
        });
        if (attr.length) reqData.attr = attr;
        if (detailText) reqData.intro = detailText;
        if (quotaNum && quotaNum !== '0') reqData.quota_num = quotaNum;

        this.request(
            {
                url: info == null ? '/supplier/product/create' : '/supplier/product/update',
                method: 'POST',
                data: reqData,
            },
            () => {
                wx.showToast({
                    title: info == null ? '添加成功' : '编辑成功',
                    icon: 'success',
                });
                const eventChannel = this.getOpenerEventChannel();
                eventChannel.emit('acceptDataFromOpenedPage');

                this.delay(() => {
                    wx.navigateBack();
                });
            },
            null,
            () => {
                this.setData({ buttonLoading: false });
            }
        );
    },
});
